package top.suyarong.ftbqsync.utils;



import java.util.concurrent.*;
import java.util.function.Function;

public class TaskPool {

    // 创建一个 ScheduledExecutorService
    protected ScheduledExecutorService executor;

    private TaskPool() {
        executor = Executors.newScheduledThreadPool(10);
    }

    private static volatile TaskPool instance;

    public static synchronized TaskPool getInstance() {
        if (instance == null) {
            synchronized (LogUtil.class) {
                if (instance == null) {
                    instance = new TaskPool();
                }
            }
        }
        return instance;
    }

    public <X, T> T runTask(Function<X, T> function, X param, long delay, TimeUnit timeUnit) {
        Future<T> future = executor.schedule(() -> function.apply(param), delay, timeUnit);
        try {
            return future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean shutdown() throws InterruptedException {
        // 停止接受新任务
        executor.shutdown();
        // 等待所有任务完成
        return !executor.awaitTermination(60, TimeUnit.SECONDS);
    }

}
